package fhb.mobile.manager.remoteDB;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.URL;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import fhb.mobile.manager.Storage;
import fhb.mobile.todoapp.datamodell.ToDoItem;
import fhb.mobile.todoapp.datamodell.ToDoItemList;
import android.os.AsyncTask;
import android.widget.Toast;

public class SyncRemoteDB extends AsyncTask<ToDoItemList, String, String> {

	protected static final String servername = "10.0.2.2/android";

	@Override
	protected String doInBackground(ToDoItemList... params) {

		ToDoItemList list = params[0];
		String request = getSyncResponse(list);

		URL fileUrl;
		try {
			fileUrl = new URL(request);
			BufferedInputStream in = new BufferedInputStream(
					fileUrl.openStream());

			byte[] data = new byte[1024];
			int x;
			String response = "";

			while ((x = in.read(data, 0, 1024)) >= 0) {
				response = response + new String(data).substring(0, x);
			}

			String[] listen = response.split("<br>");
			for (int i = 0; i < listen.length; i++) {
				switch (i) {
				case 0:
					listen[i] = listen[i].substring(1, listen[i].length() - 1);
					if (listen[i].length() != 0) {
						String[] updates = listen[i].split(",");
						for (String string : updates) {
							updateToDo(Storage.getToDo(Long.parseLong(string)));
						}
					}

					break;
				case 1:
					listen[i] = listen[i].substring(1, listen[i].length() - 1);
					if (listen[i].length() != 0) {
						String[] get = listen[i].split(",");
						for (String string : get) {
							getToDo(Long.parseLong(string));
						}
					}
					break;
				case 2:
					listen[i] = listen[i].substring(1, listen[i].length() - 1);
					if (listen[i].length() != 0) {
						String[] insert = listen[i].split(",");
						for (String string : insert) {
							insertToDo(Storage.getToDo(Long.parseLong(string)));
						}
					}
					break;
				}
			}

		} catch (IOException e) {
			Toast.makeText(Storage.getContext(), "Sync failed", 3000).show();
		}

		return "";
	}

	private String getSyncResponse(ToDoItemList doItems) {

		String request = "http://" + servername + "/sync.php?mail="
				+ Storage.getUsername() + "&0=";

		for (int i = 0; i < doItems.size(); i++) {
			request = request + doItems.get(i).getCreateDate() + "|"
					+ doItems.get(i).getLastChange() + "|";
		}

		if (doItems.size() != 0) {
			request = request.substring(0, request.length() - 1);
		}
		return request;
	}

	private void insertToDo(ToDoItem todo) throws IOException {
		String request = "http://" + servername + "/insert.php?create="
				+ todo.getCreateDate() + "&mail=" + Storage.getUsername()
				+ "&title=" + todo.getTitle() + "&content=" + todo.getContent()
				+ "&fav=" + todo.isFeatured() + "&completed="
				+ todo.isCompleted() + "&deadline=" + todo.getDeadline()
				+ "&update=" + todo.getLastChange() + "&contacts="
				+ todo.getContacts();
		request = request.replace(" ", "%20");
		request = request.replace("\n", "");
		HttpClient hc = new DefaultHttpClient();
		HttpGet post = new HttpGet(request);
		hc.execute(post);
	}

	private void updateToDo(ToDoItem todo) throws IOException {
		String request = "http://" + servername + "/update.php?create="
				+ todo.getCreateDate() + "&mail=" + Storage.getUsername()
				+ "&title=" + todo.getTitle() + "&content=" + todo.getContent()
				+ "&fav=" + todo.isFeatured() + "&completed="
				+ todo.isCompleted() + "&deadline=" + todo.getDeadline()
				+ "&update=" + todo.getLastChange() + "&contacts="
				+ todo.getContacts();
		request = request.replace(" ", "%20");
		HttpClient hc = new DefaultHttpClient();
		HttpGet post = new HttpGet(request);

		hc.execute(post);
	}

	private void getToDo(long id) throws IOException {
		String request = "http://" + servername + "/get.php?create=" + id
				+ "&mail=" + Storage.getUsername();
		request = request.replace(" ", "%20");
		HttpClient hc = new DefaultHttpClient();
		HttpGet post = new HttpGet(request);

		HttpResponse rp = hc.execute(post);
		if (rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			String str = EntityUtils.toString(rp.getEntity());
			String[] values = str.split("#");
			ToDoItem todo = new ToDoItem(Long.parseLong(values[0]),
					values[2],values[3], Long.parseLong(values[6]), false, false,
					Long.parseLong(values[7]), null);
			todo.setMail(values[1]);
			if (values[4].equals("0")) {
				todo.setCompleted(false);
			} else {
				todo.setCompleted(true);
			}
			if (values[5].equals("0")) {
				todo.setFeatured(false);
			} else {
				todo.setFeatured(true);
			}
			if ((values.length > 8)) {
				todo.setContacts(values[8]);
			}
			Storage.insertToDo(todo);
		}
	}

}
